<template>
  <div>
    <div>
      <span>选择商品分类:</span>
      <el-cascader
        size="small"
        v-model="pid"
        :options="categories"
        @change="getAttributesList"
        :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name' }"
      ></el-cascader>
    </div>
    <el-tabs v-model="activeName" @change="getAttributesList">
      <el-tab-pane
        v-for="(item, key) in tabs"
        :key="key"
        :label="item.title1 + item.title"
        :name="key"
      >
      </el-tab-pane>
    </el-tabs>
    <DF
      lw="80px "
      ref="d"
      :title="title + activeTab.title1 + activeTab.title"
      v-model="model"
      :opts="opts"
      @confirm="confirm"
    />
    <el-button
      @click="
        model = {};
        $refs.d.show();
      "
      type="primary"
      size="small"
      :disabled="!catId"
      >添加{{ activeTab.title }}</el-button
    >
    <MyTable rowkey="attr_id" :cols="cols" :data="list" :loading="queryLoading">
      <template v-slot:expand="{ row }">
        <el-tag
          class="tag"
          :key="index"
          v-for="(tag, index) in row.tags"
          closable
          @close="deleteTag(row, index)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          class="input"
          autofocus
          v-model="row.value"
          @blur="updateAttrValues(row)"
          @keyup.enter.native="updateAttrValues(row)"
          v-if="row.visible"
          :ref="'input' + row.attr_id"
          size="small"
        >
        </el-input>
        <el-button v-else size="small" @click="show(row)">+ New Tag</el-button>
      </template>
      <template v-slot:action="{ row }">
        <el-button
          type="primary"
          @click="
            model = { ...row };
            $refs.d.show();
          "
          >编辑</el-button
        >
        <el-button type="danger" @click="delAttribute(row)">删除</el-button>
      </template>
    </MyTable>
  </div>
</template>
<script>
import {
  getCategories,
  getAttributes,
  addAttributes,
  updateAttributes,
  deleteAttributes,
} from "api/goods";
export default {
  name: "params",
  data() {
    return {
      /**
       * 模型
       */
      model: {},
      /**
       * 分类ID
       */
      paramsId: [],

      activeName: "many",

      /**
       * 商品分类
       */
      categories: [],

      /**
       * 标签页
       */
      tabs: {
        many: {
          title: "参数",
          title1: "动态",
        },
        only: {
          title: "属性",
          title1: "静态",
        },
      },
    };
  },
  methods: {
    /**
     * 删除标签
     */
    async deleteTag(row, index) {
      try {
        row.tags.splice(index, 1);
        row.attr_vals = row.tags.join(" ");
        await updateAttributes(this.catId, row);
        this.getAttributesList();
        this.$m.success("删除成功");
      } catch (error) {}
    },
    /**
     *
     * 更新属性
     */
    async updateAttrValues(row) {
      if (!row.value.trim()) {
        return (row.visible = false);
      }
      try {
        row.attr_vals = row.tags.join(" ") + " " + row.value;
        await updateAttributes(this.catId, row);
        this.getAttributesList();
        this.$m.success("添加成功");
        row.value = "";
        row.visible = false;
      } catch (error) {
        console.log(error);
      }
    },

    /**
     *
     * 显示输入框
     */
    show(row) {
      row.visible = true;
      this.$nextTick(() => {
        this.$refs["input" + row.attr_id].focus();
      });
    },
    /**
     *
     * 删除属性
     */
    async delAttribute({ attr_name, attr_id }) {
      let res;
      try {
        res = await this.$myConfirm(`是否要删除【${attr_name}】!!!`);
        await deleteAttributes(this.catId, attr_id);
        this.$m.success("属性删除成功");
        this.getAttributesList();
      } catch (error) {}
      res && res();
    },
    /**
     * 提交
     */
    async confirm() {
      const d = this.$refs.d;
      try {
        d.start();
        this.queryLoading = true;
        this.queryLoading = true;
        await (this.model.attr_id ? updateAttributes : addAttributes)(
          this.catId,
          { ...this.model, attr_sel: this.activeName }
        );
        this.$m.success(this.title + "成功");
        this.getAttributesList();
        d.hide();
      } catch (error) {}
      this.queryLoading = false;
      d.stop();
    },
    /**
     * 获取参数列表
     */
    async getAttributesList() {
      try {
        if (!this.catId) {
          return this.list.splice(0, Infinity);
        }
        this.queryLoading = true;
        const list = await getAttributes(this.catId, this.activeName);
        list.forEach((item) => {
          item.tags = item.attr_vals.split(" ").filter((c) => c);
          item.value = "";
          item.visible = false;
        });
        this.list = list;
      } catch (error) {
        console.log(error);
      }
      this.queryLoading = false;
    },

    /**
     * 获取分类列表
     */
    async getCategoriesList() {
      try {
        this.categories = await getCategories();
      } catch (error) {}
    },
  },
  created() {
    this.getCategoriesList();
  },
  computed: {
    pid: {
      set(value) {
        this.paramsId = value.length < 3 ? [] : value;
      },
      get() {
        return this.paramsId;
      },
    },
    opts() {
      return {
        attr_name: {
          title: this.activeTab.title1 + this.activeTab.title,
          required: true,
          max: 20,
        },
      };
    },
    /**
     * 标题
     */
    title() {
      return this.model.attr_id ? "修改" : "添加";
    },

    /**
     * 激活配置项
     */
    activeTab() {
      return this.tabs[this.activeName];
    },
    /**
     * 分类id
     */
    catId() {
      // 如果paramsId小于三 为undefined 否则为选取params最后一个值
      return this.paramsId.length < 3 ? undefined : this.paramsId.slice(-1)[0];
    },
    /**
     * 列
     */
    cols() {
      return [
        {
          type: "expand",
          slot: "expand",
        },
        {
          title: "#",
          type: "index",
        },
        {
          title: this.activeTab.title + "名称",
          name: "attr_name",
        },
        {
          title: "操作",
          algin: "center",
          width: 300,
          slot: "action",
        },
      ];
    },
  },
};
</script>
<style  lang="scss" >
.el-scrollbar__wrap {
  height: 204px !important;
}

.input {
  width: 100px;
}
.tag {
  margin: 0 5px;
}
</style>
